<template>
  <div class="theme-detail">
    <Row class="margin-top-10">
      <p class="theme-detail__title">
        热门搜索管理
        <Button class="right" type="primary" @click="handleAdd">新增热门书籍</Button>
      </p>
      <p class="theme-detail__description">管理搜索页面热门搜索展示哪些书籍，可用作新书推荐; 下方表格拖动可以控制推荐顺序；最多可以推荐<b>10</b>本书;</p>
      <Table :columns="columns" :data="datas" :loading="loading"></Table>
      <Page
        class="pager"
        v-if="total > 0"
        :total="total"
        show-total
        show-elevator
        show-sizer
        :page-size="limit"
        @on-change="handlePageChange"
        @on-page-size-change="handlePageSizeChange"
      />
      <!-- 新增修改弹窗 -->
      <Modal
        class="common-dialog"
        v-model="showModal"
        :title="modalTitle"
        :loading="modalLoading"
        width="800"
        :mask-closable="false"
      >
        <m-book-selector-plus v-if="showModal" :value.sync="modalData" />
        <div slot="footer">
          <Button type="text" @click="handleModalCancel">取消</Button>
          <Button type="primary" @click="handleModalConfrim">确认</Button>
        </div>
      </Modal>
    </Row>
  </div>
</template>

<script>
import http from '@/utils/http';
import moment from 'moment';
// NO-COMMON
import BookSelectorPlus from '@/components/book-selector';
import ImagePreview from '@/components/uploader/components/ImagePreview';

// 模块名称
const NAME = '热门搜索书籍';
const MODULE = 'hot-search';

export default {
  name: MODULE,

  components: {
    [BookSelectorPlus.name]: BookSelectorPlus,
    [ImagePreview.name]: ImagePreview
  },

  data () {
    return {
      loading: true,
      searchStr: '',
      datas: [],
      total: 0,
      page: 1,
      limit: 10,
      columns: [
        {
          title: '序号',
          key: 'index',
          width: 80,
          align: 'center'
        },
        {
          title: '书籍ID',
          align: 'center',
          render: (h, params) => {
            return <span>{params.row.book ? params.row.book._id : '-'}</span>;
          }
        },
        {
          title: '图片',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return <ImagePreview src={params.row.book.img_url} width="40px" height="60px" style="margin: 4px auto" has-remove={false} />;
          }
        },
        {
          title: '名称',
          align: 'center',
          render: (h, params) => {
            return <span>{params.row.book.name}</span>;
          }
        },
        {
          title: '分类',
          align: 'center',
          render: (h, params) => {
            if (params.row.book.classify instanceof Array && params.row.book.classify.length > 0) {
              return params.row.book.classify.map(item => h("Tag", item));
            } else if (typeof params.row.book.classify === 'string') {
              return <Tag>{params.row.book.classify}</Tag>;
            } else {
              return <span>暂无</span>;
            }
          }
        },
        {
          title: '描述信息',
          align: 'center',
          key: 'des',
          width: 360,
          render: (h, params) => {
            return <span class="two-row-ellipsis">{params.row.book.des}</span>;
          }
        },
        {
          title: '创建时间',
          align: 'center',
          key: 'create_time',
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.create_time).format('YYYY/MM/DD HH:MM:SS')}
              </span>
            );
          }
        },
        {
          title: '操作',
          align: 'center',
          width: 200,
          key: 'handle',
          render: (h, params) => {
            return (
              <div>
                <Button
                  type="primary"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleTop(params.row)}
                >
                  置顶
                </Button>
                <Button
                  type="error"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleDelete(params.row)}
                >
                  删除
                </Button>
              </div>
            );
          }
        }
      ],
      showModal: false, // 控制modal的显隐
      modalLoading: false, // 点击modal确定按钮是否显示loading
      modalTitle: '', // modal标题
      isAddOrUpdate: '', // 是新增弹窗或者更新弹窗
      currentId: '', // 当前正在修改的商品Id
      modalData: [],
      modalError: {}
    };
  },

  methods: {
    // 获取数据
    getData () {
      this.loading = true;
      http({
        method: 'GET',
        url: `/api/admin/${MODULE}`,
        params: {
          theme: this.$route.params.id,
          page: this.page,
          limit: this.limit,
          search: this.searchStr
        },
        operation: `获取${NAME}`
      }).then(res => {
        this.loading = false;
        if (res.data && res.ok) {
          this.datas = res.data.list.map((item, index) => {
            item.index = (this.page - 1) * this.limit + index + 1;
            return item;
          });
          this.total = res.data.total;
        }
      });
    },
    // 查找数据
    findData () {
      this.limit = 10;
      this.page = 1;
      this.total = 0;
      this.getData();
    },
    // 打开新增弹窗
    handleAdd () {
      if (this.total >= 10) {
        this.$Message.error('最多只能推荐10本书籍');
        return false;
      }
      this.modalData = [];
      this.showModal = true;
      this.modalTitle = `新增${NAME}`;
      this.isAddOrUpdate = 'add';
    },
    // 置顶数据
    handleTop (item) {
      http({
        method: 'POST',
        url: `/api/admin/${MODULE}/exchange`,
        data: {
          theme: this.$route.params.id,
          book: item.book._id,
          from: item.priority,
          to: 1
        },
        operation: `置顶${NAME}`
      }).then(res => {
        if (res.data && res.ok) {
          this.$Message.success(`置顶${NAME}成功`);
          this.getData();
        }
      });
    },
    // 删除数据
    handleDelete (item) {
      this.$Modal.confirm({
        title: '温馨提示',
        content: `确定要删除此${NAME}？`,
        onOk: () => {
          http({
            method: 'DELETE',
            url: `/api/admin/${MODULE}/${item._id}`,
            operation: `删除${NAME}`
          }).then(res => {
            if (res.data && res.ok) {
              // 更新datas
              this.showModal = false;
              this.$Message.success(`删除${NAME}成功`);
              this.getData();
            }
          });
        },
        onCancel: () => {}
      });
    },
    // 自定义校验
    selfValidator (data) {
      return true;
    },
    // 取消弹窗loading
    closeModalLoading () {
      this.modalLoading = false;
      // 避免校验完直接关闭弹窗
      this.$nextTick(() => {
        this.modalLoading = true;
        this.showModal = true;
      });
    },
    handleModalConfrim () {
      http({
        method: 'POST',
        url: `/api/admin/${MODULE}`,
        data: {
          theme: this.$route.params.id,
          books: this.modalData
        },
        operation: `新增${NAME}`
      }).then(res => {
        this.modalLoading = false;
        if (res.data && res.ok) {
          this.showModal = false;
          this.$Message.success(`新增${NAME}成功`);
          this.getData();
        }
      }).catch(err => {
        this.modalLoading = false;
        this.$Message.error(`新增${NAME}失败, ${err.toString}`);
      });
    },
    handleModalCancel () {
      this.showModal = false;
    },
    // 点击分页
    handlePageChange (val) {
      this.page = val;
      this.getData();
    },
    handlePageSizeChange (size) {
      this.limit = size;
      this.getData();
    }
  },
  created () {
    this.getData();
  }
};
</script>

<style lang="scss">
.theme-detail {
  &__title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  &__description {
    font-size: 13px;
    font-weight: normal;
    margin-bottom: 20px;
    color: #666;
  }

  &__input {
    display: inline-block;
    width: 200px;
    margin-left: 20px;
    margin-right: 20px
  }

  .right {
    float: right;
  }
  .add-icon {
    float: right;
  }
  .overflow-text {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .ivu-tooltip-inner {
    max-width: inherit;
  }
  .change-btn {
    margin-right: 15px;
  }
  .modal-container {
    width: 600px;
    position: absolute;
    left: 50%;
    top: 0;
    margin-left: -300px;
  }
  .pager {
    text-align: right;
    margin-top: 30px;
  }
  .book-img {
    width: 50px;
    height: 80px;
    float: left;
    margin-right: 10px;
  }
  .book-detail > p {
    text-align: left;
    padding-right: 10px;
  }
}

.common-dialog textarea.ivu-i-input {
  font-size: 12px !important;
}
</style>
